<template>
  <el-dialog :title="title" :visible.sync="dialogvisible" width="85%" append-to-body class="my-dialog"
             :close-on-click-modal="false" @close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="110px">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="项目名称" prop="isEmpty">
            <el-input v-model="form.name" placeholder="请输入"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所在地区" prop="isEmpty">
            <el-cascader
              style="width:100%"
              :props="props"
              placeholder="选择"
              v-model="cascaderData"
              ref="address"
              clearable
              @change="handleDep()"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="地址详情" prop="isEmpty">
            <el-input
              v-model="form.address"
              type="textarea"
              maxlength="100"
              show-word-limit
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目类别" prop="isEmpty">
            <el-select
              v-model="form.cateId"
              placeholder="请选择"
              class="w100"
              clearable
            >
              <el-option
                v-for="dict in projectType"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性质" prop="isEmpty">
            <el-select
              v-model="form.type"
              placeholder="请选择"
              class="w100"
              clearable
            >
              <el-option
                v-for="dict in dict.type.sys_post_nature"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--        客户 -->
        <el-col :span="8">
          <el-form-item label="甲方信息" prop="isEmpty">
            <el-select
              :style="{width: '100%'}"
              v-model="form.customId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入甲方信息关键词"
              :remote-method="remoteMethod_user"
              :loading="loading_company">
              <el-option
                v-for="item in user_list"
                :key="item.id"
                :label="item.name || '未知'"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购方式" prop="isEmpty">
            <el-select
              v-model="form.purchaseId"
              placeholder="请选择"
              class="w100"
              clearable
            >
              <el-option
                v-for="dict in dict.type.sys_purchase_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同总价" prop="isEmpty">
            <el-input v-model="form.contractMoney" placeholder="请输入">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <!--          公司-->
          <el-form-item label="运营主体" prop="isEmpty">
            <el-input v-model="form.companyName" placeholder="请输入"/>
<!--            <el-select-->
<!--              :style="{width: '100%'}"-->
<!--              v-model="form.companyId"-->
<!--              filterable-->
<!--              remote-->
<!--              reserve-keyword-->
<!--              placeholder="请输入运营主体关键词"-->
<!--              :remote-method="remoteMethod_company"-->
<!--              :loading="loading_company">-->
<!--              <el-option-->
<!--                v-for="item in compay_list"-->
<!--                :key="item.deptId"-->
<!--                :label="item.deptName || '未知'"-->
<!--                :value="item.deptId">-->
<!--              </el-option>-->
<!--            </el-select>-->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目状态" prop="isEmpty">
            <el-select
              v-model="form.status"
              placeholder="请选择"
              class="w100"
              clearable
            >
              <el-option
                v-for="dict in dict.type.sys_post_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开始时间" prop="isEmpty">
            <el-date-picker
              v-model="form.startTime"
              class="w100"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" prop="isEmpty">
            <el-date-picker
              v-model="form.endTime" startTime
              class="w100"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-collapse v-model="activeNames">
            <el-collapse-item title="明细表" name="1">
              <div class="table-post">
                <div class="mb10">
                  <el-button type="primary" @click="addTableLine" size="small" plain>新增</el-button>
                </div>
                <div>
                  <el-table
                    :data="postList"
                  >
                    <el-table-column label="岗位" align="center">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.name" placeholder="请输入" size="small"></el-input>
                      </template>
                    </el-table-column>
<!--                    <el-table-column label="计费方式" align="center">-->
<!--                      <template slot-scope="scope">-->
<!--                        <el-select v-model="scope.row.type" placeholder="请选择" size="small">-->
<!--                          <el-option-->
<!--                            v-for="item in dict.type.sys_post_pay_method"-->
<!--                            :key="item.value"-->
<!--                            :label="item.label"-->
<!--                            :value="item.value">-->
<!--                          </el-option>-->
<!--                        </el-select>-->
<!--                      </template>-->
<!--                    </el-table-column>-->
<!--                    <el-table-column label="起始日期" align="center">-->
<!--                      <template slot-scope="scope">-->
<!--                        <el-date-picker-->
<!--                          size="small"-->
<!--                          v-model="scope.row.startTime"-->
<!--                          class="w100"-->
<!--                          value-format="yyyy-MM-dd"-->
<!--                          type="date"-->
<!--                          placeholder="请选择"-->
<!--                        ></el-date-picker>-->
<!--                      </template>-->
<!--                    </el-table-column>-->
<!--                    <el-table-column label="截止日期" align="center">-->
<!--                      <template slot-scope="scope">-->
<!--                        <el-date-picker-->
<!--                          size="small"-->
<!--                          v-model="scope.row.endTime"-->
<!--                          class="w100"-->
<!--                          value-format="yyyy-MM-dd"-->
<!--                          type="date"-->
<!--                          placeholder="请选择"-->
<!--                        ></el-date-picker>-->
<!--                      </template>-->
<!--                    </el-table-column>-->
                    <el-table-column label="人数/岗位" align="center">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.number" placeholder="请输入" size="small"></el-input>
                      </template>
                    </el-table-column>
<!--                    <el-table-column label="单价" align="center">-->
<!--                      <template slot-scope="scope">-->
<!--                        <el-input v-model="scope.row.price" placeholder="请输入" size="small"></el-input>-->
<!--                      </template>-->
<!--                    </el-table-column>-->
<!--                    <el-table-column label="金额" align="center">-->
<!--                      <template slot-scope="scope">-->
<!--                        <el-input v-model="scope.row.money" placeholder="请输入" size="small"></el-input>-->
<!--                      </template>-->
<!--                    </el-table-column>-->
                    <el-table-column label="备注" align="center">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.remark" placeholder="请输入" size="small"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="60">
                      <template slot-scope="scope">
                        <el-button @click="detelBtn(scope.$index)" size="small" plain type="text">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-col>
        <el-col :span="8">
          <el-form-item label="履约保证金形式" prop="name">
            <el-select v-model="form.depositType" placeholder="请选择" size="small" class="w100">
              <el-option
                v-for="item in dict.type.sys_deposit_type"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="缴纳日期">
            <el-date-picker
              size="small"
              v-model="form.depositDate"
              class="w100"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="履约保证金金额">
            <el-input v-model="form.deposit" placeholder="请输入" size="small">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="履约保证金状态">
            <el-select v-model="form.depositStatus" placeholder="请选择" size="small" class="w100">
              <el-option
                v-for="item in dict.type.sys_deposit_status"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              type="textarea"
              maxlength="100"
              show-word-limit
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" size="small" plain>确 定</el-button>
      <el-button @click="cancel" size="small" plain>取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getProject,
  addProject,
  updateProject
} from "@/api/system/project";
import {listCustom, getCustom} from '@/api/system/custom.js'
import {listProjectPost} from "@/api/system/project";
import {listUser} from '@/api/system/user'
import {citysMana} from "@/api/system/config"
import {listDept, getDept} from "@/api/system/dept";
import {listProjectType} from "@/api/system/project";
import {listPost} from "@/api/system/post";
import {mapGetters} from 'vuex'

export default {
  name: "detail",
  dicts: ['sys_stagnation_type', 'sys_purchase_type', 'sys_post_nature', 'sys_deposit_type', 'sys_deposit_status', 'sys_post_pay_method', 'sys_post_status'],
  props: ['visible', 'param'],
  data() {
    return {
      // 弹出层标题
      title: "编辑项目信息",
      // 是否显示弹出层
      dialogvisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postCode: undefined,
        postName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        isEmpty: [
          {required: true, message: "数据不能为空", trigger: "blur"}
        ],
      },
      props: {
        lazy: true,
        label: "name",
        value: "id",
        lazyLoad: this.lazyLoad,
      },
      cascaderData: [], // 地址值
      postList: [],
      activeNames: ['1'],
      loading_company: false,
      compay_list: [],
      loading_user: false,
      user_list: [],
      projectType: [], // 项目类型/类别
      jobList: []
    };
  },
  computed: {
    ...mapGetters([
      'deptId',
      'userId'
    ]),
  },
  watch: {
    visible() {
      this.dialogvisible = this.visible
      this.reset()
      if (this.visible) {
        this.getProjectType() // 项目类型
        this.postList.push({
          deptId: this.deptId,
          postId: '', // 岗位id
          type: '', // 计费方式1-年;2-季度;3-月;4-天;5-小时
          startTime: '', //
          endTime: '', //
          number: '', // 人数
          price: '', // 单价
          money: '', // 总价
          remark: '', //
        })
        console.log('this.param:', this.param)
        if (this.param) {
          this.getDetail()
        }
      }
    }
  },
  created() {
  },
  methods: {
    /** 详情 */
    getDetail() {
      getProject(this.param.id).then(response => {
        response.data.detail.depositStatus = response.data.detail.depositStatus.toString()
        response.data.detail.purchaseId = response.data.detail.purchaseId.toString() // 采购方式
        response.data.detail.depositType = response.data.detail.depositType.toString() // 履约保证金形式
        response.data.detail.cateId = response.data.detail.cateId.toString() // 类型
        response.data.detail.type = response.data.detail.type.toString() // 性质 性质：1自营，2挂靠
        this.cascaderData = [response.data.detail.provinceId, response.data.detail.cityId, response.data.detail.districtId]
        for (let item of response.data.detail.projectPostList) {
          item.type = item.type?item.type.toString():''
        }
        this.postList = this.$deepCopy(response.data.detail.projectPostList)

        this.form = response.data.detail;
        this.form.isEmpty = '1'
        // this.getCompanyDetail()
        this.getUserDetail()
      });
    },
    // 地址
    async lazyLoad(node, resolve) {
      let parentId = 100;
      if (node.level !== 3) {
        if (node.level) {
          parentId = node.value;
        }
        let res = await citysMana({
          parentId: node.data ? node.data.id : 1
        });
        if (node.level == 2) {
          for (let item of res.rows) {
            item.leaf = true;
          }
        }
        resolve(res.rows);
      }
    },
    // 客户搜素
    remoteMethod_kehu(query) {
      this.loading_kehu = true
      listCustom({
        pageNum: 1,
        pageSize: 10,
        name: query
      }).then(response => {
        this.kehu_list = response.rows;
        this.loading_kehu = false
      });
    },
    // 负责人搜索
    remoteMethod_fuzeren(query, id) {
      this.loading_kehu = true
      let query_ = {
        pageNum: 1,
        pageSize: 10,
      }
      if (query !== 'edit') {
        query_.userId = id
      } else {
        query_.nickName = query
      }
      listUser(query_).then(response => {
        this.fuzeren_list = response.rows;
        this.loading_kehu = false
      });
    },
    // 地址变化徽调
    handleDep(option) {
      if (this.$refs["address"].getCheckedNodes().length) {
        let id_ = this.$refs["address"].getCheckedNodes()[0].path;
        let name_ = this.$refs["address"].getCheckedNodes()[0].pathLabels;
        this.form.provinceId = id_[0]
        this.form.cityId = id_[1]
        this.form.districtId = id_[2]
        this.form.province = name_[0]
        this.form.city = name_[1]
        this.form.district = name_[2]
      } else {
        this.form.provinceId = ''
        this.form.cityId = ''
        this.form.districtId = ''
        this.form.province = ''
        this.form.city = ''
        this.form.district = ''
      }
    },
    changeFuzeren(option) {
      if (!option) {
        this.form.leader = ''
        return
      }
      for (let item of this.fuzeren_list) {
        if (item.userId == option) {
          this.form.leader = item.nickName
          this.form.phone = item.phonenumber
        }
      }
    },
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          let data_ = JSON.parse(JSON.stringify(this.form))
          if (!data_.name) {
            this.$message.error('项目名称不能为空')
            return
          }
          if (!this.cascaderData.length) {
            this.$message.error('所在地区不能为空')
            return
          }
          if (!data_.address) {
            this.$message.error('地址详情不能为空')
            return
          }
          if (!data_.cateId) {
            this.$message.error('项目类别不能为空')
            return
          }
          if (!data_.type) {
            this.$message.error('性质不能为空')
            return
          }
          if (!data_.customId) {
            this.$message.error('甲方信息不能为空')
            return
          }
          if (!data_.purchaseId) {
            this.$message.error('采购方式不能为空')
            return
          }
          if (!data_.contractMoney) {
            this.$message.error('合同总价不能为空')
            return
          }
          if (!this.isNumeric(data_.contractMoney)) {
            this.$message.error('请确保合同总价值为数字类型')
            return
          }
          if (!data_.companyName) {
            this.$message.error('运营主体不能为空')
            return
          }
          if (!data_.startTime) {
            this.$message.error('开始时间不能为空')
            return
          }
          if (!data_.endTime) {
            this.$message.error('结束时间不能为空')
            return
          }
          let list_ = this.$deepCopy(this.postList)
          for (let item of list_) {
            if (!item.name) {
              this.$message.error('岗位名称不能为空')
              return
            }
            if (item.number && !this.isNumeric(item.number)) {
              this.$message.error('请确保岗位人数值为数字类型')
              return
            }
            if(!item.type){
              item.type = 0
            }
          }
          if (data_.deposit && !this.isNumeric(data_.deposit)) {
            this.$message.error('请确保履约保证金金额值为数字类型')
            return
          }
          data_.projectPostList = this.$deepCopy(list_)
          data_.userId = this.userId
          delete data_.isEmpty

          if (data_.id != undefined) {
            updateProject(data_).then(response => {
              this.$emit('getList')
              this.$modal.msgSuccess("修改成功");
              this.cancel();
            });
          } else {
            addProject(data_).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$emit('getList')
              this.cancel();
            });
          }
        }
      });
    },
    isNumeric(value) {
      return !isNaN(parseFloat(value)) && isFinite(value);
    },
    cancel() {
      this.$emit('update:visible', false)
    },
    reset() {
      this.form = {
        deptId: '', // 所属组织
        parentId: 0, // 上级id
        cateId: '', // 类型
        type: '', // 性质 性质：1自营，2挂靠
        provinceId: '', // 省id
        province: '', // 省
        cityId: '', // 市ID
        city: '', //  市
        districtId: '', // 区ID
        district: '', // 区
        address: '', // 地址
        name: '', // 名称
        status: '0',
        companyName: '', // 公司id
        customd: '', // 客户id
        purchaseId: '', // 采购方式:1-公开招投标;2-邀标;3-议标;4-直接分包;5-报价
        contractMoney: '', // 合同金额
        depositType: '', // 履约保证金形式：1转账形式2投标保证金转换3无
        depositDate: '', // 缴纳日期
        deposit: '', // 保证金金额
        depositStatus: '', // 保证金状态
        remark: '', //  备注
        startTime: '', // 项目开始时间
        endTime: '', // 项目结束时间
        projectPostList: '', // 岗位信息
        isEmpty: '1',
        userId: 0
      }
      this.resetForm("form");
      this.postList = []
    },
    // 查询客户信息
    remoteMethod_user(query) {
      this.loading_user = true
      let query_ = {
        pageNum: 1,
        pageSize: 10,
        name: query
      }
      listCustom(query_).then(response => {
        this.user_list = response.rows;
        this.loading_user = false
      });
    },
    // 客户详情
    getUserDetail() {
      getCustom(this.form.customId).then(res => {
        this.user_list = [{
          id: Number(res.data.id),
          name: res.data.name
        }]
      })
    },
    // 查询运营主体信息
    remoteMethod_company(query) {
      this.loading_cmpany = true
      let query_ = {
        pageNum: 1,
        pageSize: 10,
        deptName: query,
        type: 1 // 固定类型
      }
      listDept(query_).then(response => {
        this.compay_list = response.data;
        this.loading_cmpany = false
      });
    },
    // 公司详情
    getCompanyDetail() {
      getDept(this.form.companyId).then(res => {
        this.compay_list = [{
          deptId: res.data.deptId,
          deptName: res.data.deptName
        }]
      })
    },
    // 项目类型/类别 listProjectType
    getProjectType() {
      listProjectType(this.queryParams).then(response => {
        this.projectType = response.rows;
      });
    },
    // 项目岗位 listPost
    getPost() {
      listProjectPost({
        pageNum: 1,
        pageSize: 100,
      }).then(response => {
        this.jobList = response.rows;
      });
    },
    handleSelectionChange(selection) {
      console.log('selection:', selection)
      // this.ids = selection.map(item => item.postId)
      // this.single = selection.length != 1
      // this.multiple = !selection.length
    },
    // 新增岗位
    addTableLine() {
      this.postList.push({
        deptId: this.deptId,
        name: '', // 岗位id
        type: '', // 计费方式1-年;2-季度;3-月;4-天;5-小时
        startTime: '', //
        endTime: '', //
        number: '', // 人数
        price: '', // 单价
        money: '', // 总价
        remark: '', //
      })
    },
    detelBtn(index) {
      this.postList.splice(index, 1)
    },
  }
}
</script>

<style scoped>

</style>
